package com.cti.ftpservice.serviceImpl;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import javax.management.RuntimeErrorException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.cti.ftpservice.ftp.FTPDownFiles;
import com.cti.ftpservice.ftp.FileUtils;
import com.cti.ftpservice.model.FtpConfigInfo;
import com.cti.ftpservice.model.FtpFileInfo;
import com.cti.ftpservice.model.FtpServiceInfo;
import com.cti.ftpservice.service.FtpService;
import com.cti.ftpservice.utils.FtpWsManagerUtil;
import com.ctibook.booksystem.ws.FtpFileDownloadViewVo;
import com.ctibook.booksystem.ws.FtpFileInfoViewVo;
import com.ctibook.booksystem.ws.FtpFileUploadInfoViewVo;
import com.ctibook.booksystem.ws.FtpServiceUploadFtpFilesViewVo;
import com.ctibook.booksystem.ws.FtpServiceViewVo;
import com.ctibook.booksystem.ws.FtpServiceWSProxy;

@Service("ftpService")
public class FtpServiceImpl implements FtpService {

	private static Log logger = LogFactory.getLog(FtpServiceImpl.class);
	@Autowired
	private FtpConfigInfo ftpConfigInfo;
	@Override
	public void downloadFilesFromFtpServices() {
		String savePath=ftpConfigInfo.getFileSavePathRoot();
		FtpServiceViewVo[] ftpServiceViewVos= FtpWsManagerUtil.getFtpServiceViewVosByTypeFromProxy(FtpServiceInfo.FtpServiceType_DownloadFile);
		if(ftpServiceViewVos!=null&&ftpServiceViewVos.length>0){
			for (FtpServiceViewVo ftpServiceViewVo : ftpServiceViewVos) {
	        	 try {
	        		 FtpServiceInfo ftpDownLoadParams=new FtpServiceInfo();
		        	 ftpDownLoadParams.setFtpport(ftpServiceViewVo.getPort());
		        	 ftpDownLoadParams.setFtpURL(ftpServiceViewVo.getUrl());
		        	 ftpDownLoadParams.setUsername(ftpServiceViewVo.getUserName());
		        	 ftpDownLoadParams.setPwd(ftpServiceViewVo.getPassWrod());
		        	 String ftpServiceFileSavePath=savePath+ftpServiceViewVo.getFtpServiceName();
		        	 ftpDownLoadParams.setSavePath(ftpServiceFileSavePath);
		        	 ftpDownLoadParams.setId(ftpServiceViewVo.getId());
		        	 ftpDownLoadParams.setThreadCount(5);
		        	 String[] files=ftpServiceViewVo.getDownloadFilePaths();
		        	 FtpFileDownloadViewVo[] hasDownLoadFiles= FtpWsManagerUtil.getFtpDownloadFileViewVoByFtpServiceIdAndDownloadPath(ftpServiceViewVo.getId(), files);
		    		 List<FtpFileInfo> fileResultPaths= FileUtils.getFilesFromFilePaths(files,ftpServiceViewVo,ftpServiceFileSavePath);
		    		 Queue<FtpFileInfo> downloadFiles= new LinkedList<FtpFileInfo>();
		    		 for (FtpFileInfo file : fileResultPaths) {
		    			 boolean flag=true;
		    			 if(hasDownLoadFiles!=null&&hasDownLoadFiles.length>0){
		    				 for (FtpFileDownloadViewVo hasDownLoadFile : hasDownLoadFiles) {
									if(hasDownLoadFile.getDownloadFtpFilePath().equals(file.getFtpServicePath())
										&& hasDownLoadFile.getDownloadFtpFileSize()==file.getFileSize())
										flag=false;
								}
		    			 }
		    			if(flag)
		    			 downloadFiles.offer(file);
					 }
		    		 ftpDownLoadParams.setDownFileInfos(downloadFiles);
		    		 ftpDownLoadParams.setBookTotalCount(fileResultPaths.size());
					 ftpDownLoadParams.startDownLoad();
				} catch (Exception e) {
					logger.error(e.getMessage());
				} 
			}
		}
	}

	@Override
	public void saveFtpDownloadFileToDB() {
		try{
			String downloadFileSaveXmlPathRoot=System.getProperty("user.dir")+ftpConfigInfo.getFtpDownloadFileSaveXmlPathRoot();
			File  fileRoot = new File(downloadFileSaveXmlPathRoot);
			DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();   
		    DocumentBuilder builder=factory.newDocumentBuilder();  
		    FtpServiceWSProxy ftpWs=new FtpServiceWSProxy();
			if(fileRoot.exists()){
				File[] xmlFiles=fileRoot.listFiles();
				for(File file :xmlFiles){
					List<FtpFileInfoViewVo> ftpFileVos=	getFtpDownloadFileInfoFromXml(file,builder);
					for(FtpFileInfoViewVo vo :ftpFileVos){
						ftpWs.addOrUpdateFtpFileInfoViewVo(vo);
					}
				}
				for (int i = 0; i < xmlFiles.length; i++) {
					xmlFiles[i].delete();
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	private List<FtpFileInfoViewVo>  getFtpDownloadFileInfoFromXml(File file ,DocumentBuilder builder) throws ParseException{
		List<FtpFileInfoViewVo> ftpFileVos= new ArrayList<FtpFileInfoViewVo>();
        try {
			Document doc = builder.parse(file);
			Element root=doc.getDocumentElement();
			String ftpServiceId=root.getAttribute("id");
			NodeList childNodes=doc.getElementsByTagName("FileInfo");
			for(int i=0;i<childNodes.getLength();i++){
				Element ele = (Element)childNodes.item(i);
				FtpFileInfoViewVo vo = new FtpFileInfoViewVo();
				vo.setFtpServiceId(ftpServiceId);
				vo.setApprovedByHuman(false);
				vo.setFlieType("extension");
				vo.setExtension(ele.getAttribute("extension"));
				vo.setFileName(ele.getAttribute("name"));
				vo.setLocalFtpFilePath(ele.getAttribute("localFtpPath"));
				vo.setDownloadFtpFilePath(ele.getAttribute("ftpServicePath"));
				vo.setDownloadDate(ele.getAttribute("date"));
				vo.setFileSize(Integer.parseInt(ele.getAttribute("fileSize")));
				ftpFileVos.add(vo);
			}
		} catch (SAXException e) {
			e.printStackTrace();
			ftpFileVos.clear();
		} catch (IOException e) {
			e.printStackTrace();
			ftpFileVos.clear();
		}  
        return ftpFileVos;
	}
	

	public void uploadFilesToFtpServices(){
		FtpServiceUploadFtpFilesViewVo[] ftpServiceViewVos= FtpWsManagerUtil.getFtpServiceUploadFtpFileInfo();
		if(ftpServiceViewVos!=null&&ftpServiceViewVos.length>0){
			for (FtpServiceUploadFtpFilesViewVo ftpServiceViewVo : ftpServiceViewVos) {
	        	 try {
	        		 FtpServiceInfo ftpUpLoadParams=new FtpServiceInfo();
	        		 ftpUpLoadParams.setFtpport(ftpServiceViewVo.getFtpServiceViewVo().getPort());
	        		 ftpUpLoadParams.setFtpURL(ftpServiceViewVo.getFtpServiceViewVo().getUrl());
	        		 ftpUpLoadParams.setUsername(ftpServiceViewVo.getFtpServiceViewVo().getUserName());
	        		 ftpUpLoadParams.setPwd(ftpServiceViewVo.getFtpServiceViewVo().getPassWrod());
	        		 ftpUpLoadParams.setId(ftpServiceViewVo.getFtpServiceViewVo().getId());
	        		 ftpUpLoadParams.setFtpServiceName(ftpServiceViewVo.getFtpServiceViewVo().getFtpServiceName());
	        		 ftpUpLoadParams.setThreadCount(5);
		        	 FtpFileUploadInfoViewVo[] uploadFilePaths= ftpServiceViewVo.getUploadFtpFileVos();
		    		 Queue<FtpFileUploadInfoViewVo> uploadFiles= new LinkedList<FtpFileUploadInfoViewVo>();
		    		 for (FtpFileUploadInfoViewVo file : uploadFilePaths) {
		    			 uploadFiles.offer(file);
					 }
		    		 ftpUpLoadParams.setUploadFilePaths(uploadFiles);
		    		 ftpUpLoadParams.setBookTotalCount(uploadFilePaths.length);
		    		 ftpUpLoadParams.startUpLoad();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}
